package com.shanghaionstar.smart.presenter;

import android.text.TextUtils;

import com.midea.iot.sdk.cloud.openapi.MSmartSDK;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.smart.GetSmartDeviceDetailResponse;
import com.onstar.cn.smart.GetSmartDeviceResponse;
import com.onstar.cn.smart.SmartDevicesResponse;
import com.onstar.cn.smart.SmartTokenResponse;
import com.onstar.cn.weight.ToastView;
import com.shanghaionstar.R;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.smart.SmartAddDeviceFrg;
import com.shanghaionstar.smart.SmartHomeActivity;
import com.shanghaionstar.smart.SmartIntroduceFrg;
import com.shanghaionstar.smart.SmartTriggerFrg;
import com.shanghaionstar.smart.iview.ISmartListView;
import com.shanghaionstar.smart.service.SmartHomeService;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.NetConnectUtil;

import java.util.ArrayList;
import java.util.List;

import rx.functions.Action1;

/**
 * Created by 7828wc on 2016/6/22.
 */
public class SmartDeviceListPresenter extends BasePresenter<Object> {
    private BaseActivity mContext;
    private ISmartListView mSmartListView;
    private SmartHomeService service;
    private List<GetSmartDeviceResponse> mSmartDevices = new ArrayList<>();
    private SmartDevicesResponse mSmartDevicesRes;

    public SmartDeviceListPresenter(IMVPScheduler mvpScheduler) {
        super(mvpScheduler);
    }

    @Override
    public void setView(IMVPView<Object> view) {
        super.setView(view);
        mSmartListView = (ISmartListView) view;
        mContext = (BaseActivity) mSmartListView.onActivity();
        service = new SmartHomeService(mContext);
    }

    public void getSmartDevices() {
        subscription = service.getSmartDevices().subscribeOn(mvpScheduler.backgroundThread()).observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<SmartDevicesResponse>() {
                    @Override
                    public void call(SmartDevicesResponse response) {
                        mSmartListView.setLoading(false);
                        if(response != null) {
                            mSmartDevicesRes = response;
                            mSmartDevices = mSmartDevicesRes.devices;
                            if (mSmartDevices != null && !mSmartDevices.isEmpty()) {
                                mSmartListView.initData(mSmartDevicesRes);
                            }
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        mSmartListView.setLoading(false);
                        if (throwable != null)
                            mSmartListView.onResponseError((OnStarException) throwable);
                    }
                });
    }


    public void getSmartDeviceDetail(String deviceId, String deviceType, final int index) {
        mSmartListView.setLoading(true);
        subscription = service.getSmartDeviceDetail(deviceId, deviceType).subscribeOn(mvpScheduler.backgroundThread()).observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<GetSmartDeviceDetailResponse>() {
                    @Override
                    public void call(GetSmartDeviceDetailResponse detailResponse) {
                        mSmartListView.setLoading(false);
                        GetSmartDeviceResponse smartDeviceResponse = mSmartDevicesRes.devices.get(index);
                        smartDeviceResponse.profiles = detailResponse.profiles;
                        smartDeviceResponse.switchStatus = detailResponse.switchStatus;
                        mSmartListView.notifyDataChange();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        mSmartListView.setLoading(false);
                        mSmartListView.onGetDetailError(throwable);
                    }
                });
    }


    /**
     * 获取第三方token
     */
    public void getToken() {
        mSmartListView.setLoading(true);
        RequestEntity entity = NetConnectUtil.getAuthRequestEntity(mContext);
        subscription = service.getToken(entity).subscribeOn(mvpScheduler.backgroundThread()).observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<SmartTokenResponse>() {
                    @Override
                    public void call(SmartTokenResponse response) {
                        mSmartListView.setLoading(false);
                        String mAccessToken =  response.accessToken;
                        mAccessToken =  MSmartSDK.getInstance().getThirdManager().decodeAccessToken(mAccessToken);
                        ((SmartHomeActivity) mContext).mAccessToken = mAccessToken;
                        if (TextUtils.isEmpty(((SmartHomeActivity) mContext).mAccessToken)) {
                            new ToastView(mContext).showToast(mContext.getString(R.string.smart_get_token_failed));
                        } else {
                            goToAddDevice();
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        mSmartListView.setLoading(false);
                        String errorMsg = throwable.getMessage();
                        new ToastView(mContext).showToast(errorMsg == null ?mContext.getString(R.string.smart_get_token_failed) : errorMsg);
                    }
                });
    }


    private void goToAddDevice() {
        SmartAddDeviceFrg addFrg = new SmartAddDeviceFrg();
        mContext.changeFragment(mContext.getSupportFragmentManager(), addFrg, SmartAddDeviceFrg.class, true);
    }

    public void groupClick(int groupPosition) {
        final GetSmartDeviceResponse smartDevice = mSmartDevicesRes.devices.get(groupPosition);
        final String deviceId = smartDevice.deviceId;
        final String deviceType = smartDevice.deviceType;
        final int index = groupPosition;
        if (!TextUtils.isEmpty(deviceId)) {
            getSmartDeviceDetail(deviceId, deviceType, index);
        }
    }

    public void goToFunIntro() {
        BusinessUtil.sendReportByClickType(mContext, FunctionNameFindId.Smarthome_introduction_tapin.getStringValue());
        SmartIntroduceFrg introFrg = new SmartIntroduceFrg();
        mContext.changeFragment(mContext.getSupportFragmentManager(), introFrg, SmartIntroduceFrg.class, true);
    }

    public void goToTrigger() {
        BusinessUtil.sendReportByClickType(mContext, FunctionNameFindId.Smarthome_applistdetail_gofence.getStringValue());
        SmartTriggerFrg triggerFrg = new SmartTriggerFrg();
        mContext.changeFragment(mContext.getSupportFragmentManager(), triggerFrg, SmartTriggerFrg.class, true);
    }

    public void addClick() {
        BusinessUtil.sendReportByClickType(mContext, FunctionNameFindId.Smarthome_addappliance.getStringValue());
        if (TextUtils.isEmpty(((SmartHomeActivity) mContext).mAccessToken)) {
            getToken();
        } else {
            goToAddDevice();
        }
    }

    public void onMenuItemClick(final int groupPostion) {
        try {
            BusinessUtil.sendReportByClickType(mContext, FunctionNameFindId.Smarthome_deleteappliance.getStringValue());
            String deviceId = mSmartDevicesRes.devices.get(groupPostion).deviceId;
            mSmartListView.setLoading(true);
            subscription = service.unBindDevice(deviceId).subscribeOn(mvpScheduler.backgroundThread()).observeOn(mvpScheduler.mainThread())
                    .subscribe(new Action1<String>() {
                        @Override
                        public void call(String json) {
                            mSmartListView.setLoading(false);
                            if (json != null && json.contains("E0000")) {
                                mSmartDevicesRes.devices.remove(groupPostion);
                                mSmartListView.notifyDataChange();
                            }

                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            mSmartListView.setLoading(false);
                            if (throwable != null)
                                mSmartListView.onResponseError((OnStarException) throwable);
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}



